﻿using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Koala.Pro.CodeGenerator.UI.Common;
using Koala.Pro.CodeGenerator.UI.DatabaseModel.Data;

namespace Koala.Pro.CodeGenerator.UI.DatabaseModel
{
    public sealed class DatabaseFactory
    {
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        public static IListData Create(string databaseType)
        {
            if (databaseType == null)
            {
                throw new ArgumentNullException("databaseType");
            }
            IListData listData = null;
            object obj = null;
            string path = "DatabaseSetting.xml";
            if (!File.Exists(path))
            {
                throw new FileNotFoundException("Can not find the file: DatabaseSetting.xml");
            }
            try
            {
                DatabaseSetting[] array = (DatabaseSetting[])XmlUtils.LoadObjectFromXml(path, typeof(DatabaseSetting[]));
                DatabaseSetting[] array2 = array;
                foreach (DatabaseSetting databaseSetting in array2)
                {
                    if (databaseType == databaseSetting.DatabaseType)
                    {
                        obj = Assembly.Load(databaseSetting.AssemblyName).CreateInstance(databaseSetting.AssemblyType);
                        listData = obj as IListData;
                        if (listData != null)
                        {
                            listData.ConnectString = databaseSetting.ConnectString;
                        }
                        break;
                    }
                }
            }
            catch (Exception exception)
            {
                log.Error("Initialize the assembly error, please check the settting file: DatabaseSetting.xml", exception);
            }
            return listData;
        }
    }

}
